package com.huitone.smspfm.oldclient.asclient.send;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;

import com.huitone.smspfm.oldclient.logger.ExtLogger;

import com.bin.common.utils.DateTimeUtils;
import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.context.app.AppManager;
import com.huitone.smspfm.context.thread.AppCustomBlockingThreadPool;
import com.huitone.smspfm.context.utils.ContextPropertiesUtils;
import com.huitone.smspfm.oldclient.app.AppStaticConfigs;
import com.huitone.smspfm.oldclient.model.MtGroup;
import com.huitone.smspfm.oldclient.model.MtSms;
import com.huitone.smspfm.oldclient.store.MtGroupTmpStore;
import com.huitone.smspfm.oldclient.store.MtTmpStore;
import com.huitone.smspfm.socket.client.SocketClient;
import com.huitone.smspfm.socket.protocol.sgip.constant.CommandID;
import com.huitone.smspfm.socket.protocol.sgip.constant.Constant;
import com.huitone.smspfm.socket.protocol.sgip.message.Message;
import com.huitone.smspfm.socket.protocol.sgip.message.msgbody.Submit2;
import com.huitone.smspfm.socket.protocol.sgip.message.msghead.Head;
import com.huitone.smspfm.socket.utils.SerialUtils;


/**   
* @Title: SendMsgThread.java 
* @Package com.unicom.gddw.oldplatform 
* @Description: TODO 旧平台兼容程序管理器,读取xml文件的短信并发送
* @author ybliang   
* @date 2017年3月9日 下午3:21:40 
* @version V1.0   
*/
public class SendMsgOldManager extends Thread {
	
	private final static ExtLogger logger = ExtLogger.create(SendMsgOldManager.class);

	private static SendMsgOldManager instance = new SendMsgOldManager();
	
	private ExecutorService fixedThreadPool = null;
	
	private ExecutorService fixedThreadPool2 = AppCustomBlockingThreadPool.newBlockingThreadPool(100);
	
	private boolean toSleep = false;
	private long sleepTime = 1000;
	
	private String fileDir = null;
	
	private String fileRegex = null;
	
	public static SendMsgOldManager getInstance() {
		return instance;
	}
	
	private SendMsgOldManager() {}

	@Override
	public void run() {
		
		logger.info("启动旧平台短信发送线程。");
		
		fileDir = ContextPropertiesUtils.getProperty("smspfm.client.file.dir.mt");
		fileRegex = ContextPropertiesUtils.getProperty("smspfm.client.file.name.regex");
		
		fixedThreadPool = AppCustomBlockingThreadPool.newBlockingThreadPool(
				StringUtils.toInteger(ContextPropertiesUtils.getProperty("smspfm.client.send.poolSize"),3,true));
		
		while(AppManager.isRunning() && !this.isInterrupted()) {
			
			fixedThreadPool.execute(new Runnable() {
				
				@Override
				public void run() {
					
					MtFileReader fileReader = new MtFileReader();
					
					StringBuffer buffer = fileReader.readFile(fileDir, fileRegex);
					
					Map<String, MtGroup> map = MtSms.parse(buffer);
					
					if (!map.isEmpty()) {
						
						Iterator<Entry<String, MtGroup>> iterator = map.entrySet().iterator();
						
						while(iterator.hasNext()) {
							MtGroup mtGroup = iterator.next().getValue();
							
							if (mtGroup.sendAble()) {
								// 如果短信当前是可发送的则进行发送(注:一般不可发送是因为长短信剩余分段没有读取到,可能的原因是长短信分段跨文件了)
								
								MtSms mtSms = mtGroup.merged();
								try {
									
									String serviceCode = AppStaticConfigs.serviceCode;
									if (AppStaticConfigs.isUseOldServiceCode) {
										serviceCode = mtSms.getServiceCode();
									}
									
									Submit2 submit = Submit2.build(mtSms.getMobileno(), AppStaticConfigs.srvNode, serviceCode, 
											mtSms.getSendport(), 1, Constant.MessageCodingE.GBK.getValue(), 
											Constant.MessageTypeE.SMS.getValue(), mtSms.getContent(), mtSms.getClientname(), mtSms.getOldserialnos());
									Head head = Head.build(submit.length(), CommandID.SGIP_SUBMIT2, AppStaticConfigs.codeRule, StringUtils.toIntegerP(DateTimeUtils.dateToStr(new Date(), "MMddHHmmss")), SerialUtils.getSerial());
									
									String serialNo = head.getSerialNo();
									
									mtSms.setSerialno(serialNo);
									mtSms.setSrvNode(AppStaticConfigs.srvNode);
									mtSms.setServiceCode(serviceCode);
									mtSms.setReportflag(1);
									mtSms.setCoderule(head.getSerialNoPart1());
									mtSms.setDatetime(head.getSerialNoPart2());
									mtSms.setSeqnumber(head.getSerialNoPart3());
									mtSms.setiSendTimes(1);
									mtSms.setLastSendTime(new Date());
									
									MtTmpStore.put(serialNo, mtSms);
									
									boolean status = SocketClient.getInstance().sendMsg(head, submit);
									
									logger.submit(new Message(head, submit).toString() + " status:" + status);
									
								} catch (Exception e) {
									logger.error("短信发送时发生错误:" + mtSms.toString(), e);
								}
							} else {
								// 长短信分段没有读齐,放入临时存储队列等待长短信分段读取完整
								fixedThreadPool2.execute(new Runnable() {
									
									@Override
									public void run() {
										MtGroupTmpStore.add(mtGroup);
									}
								});
							}
						}
						toSleep = false;
					} else {
						toSleep = true;
					}
					
					if (AppStaticConfigs.backupSmsFiles) {
						fileReader.setBackupFile(true);
					}
					
					fileReader.remove();
				}
			});
			
			try {
				if (toSleep) {
					Thread.sleep(sleepTime);
				}
			} catch (InterruptedException e) {
				break;
			}
		}
		
		logger.info("旧平台短信发送线程退出。");
	}

	public void shutdown() {
		if (fixedThreadPool != null) {
			fixedThreadPool.shutdown();
		}
		if (fixedThreadPool2 != null) {
			fixedThreadPool2.shutdown();
		}
	}
}
